package ex14.pyrmont.startup;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

	public static final int PORT = 8005;

	public static void main(String[] args) throws Exception {

		ServerSocket s = new ServerSocket(PORT);
		System.out.println("Started: " + s);
		try {
			Socket socket = s.accept();
			try {
				System.out.println("Connection accepted: " + socket);
				BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),
						true);
				while (true) {
					String str = in.readLine();
					if (str.equals("END"))
						break;
					System.out.println("Echoing: " + str);
					out.println(str);
				}
				// Always close the two sockets...
			} finally {
				System.out.println("closing...");
				socket.close();
			}
		} finally {
			s.close();
		}

		// ServerSocket serverSocket = null;
		// serverSocket = new ServerSocket(PORT);
		//
		// // while (true) {
		//
		// Socket socket = null;
		// socket = serverSocket.accept();
		// System.out.println("连接客户机" + socket.getRemoteSocketAddress());
		// // 用于接收客户端发来的数据的输入流
		// BufferedReader reader = new BufferedReader(new
		// InputStreamReader(socket.getInputStream()));
		//
		// BufferedWriter writer = new BufferedWriter(new
		// OutputStreamWriter(socket.getOutputStream()));
		//
		// System.out.println("服务器接收到客户端的连接请求：" + reader.readLine());
		//
		// writer.write("hello");
		//
		// socket.close();
		// serverSocket.close();
		// // }
	}
}
